﻿///<reference path="../_ref.js"/>
var app = app || {};

app.LibraryView = Backbone.View.extend({
    el: '#books',

    initialize: function (initialBooks) {
        this.collection = new app.Library(initialBooks);
        this.render();

        this.listenTo(this.collection, 'add', this.renderBook);
    },

    events: {
        "click #add": 'addBook'
    },

    addBook: function (e) {
        e.preventDefault();
        var formData = {};
        $('#addBook').children('input').each(function (i, el) {
            var $el = $(el);
            if ($el.val() != '') {
                formData[el.id] = $el.val();
                $el.val('');
            }
        });

        this.collection.add(new app.Book(formData));
    },

    render: function () {
        this.collection.each(function (item) {
            this.renderBook(item);
        }, this);
    },

    renderBook: function (book) {
        var bookView = new app.BookView({ model: book });
        this.$el.append(bookView.render().el);
    }
});